package com.af.community.smart.base

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.IBinder
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.annotation.LayoutRes
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.af.community.smart.business.R
import com.af.community.smart.event.IBaseViewEventObserver
import com.af.community.smart.utils.ActivityStack
import com.github.zackratos.ultimatebar.ultimateBarBuilder
import net.idik.lib.slimadapter.SlimAdapter
import net.idik.lib.slimadapter.SlimAdapterEx

open class BaseActivity : AppCompatActivity(),
    IBaseViewEventObserver,
    TextWatcher,
    View.OnClickListener,
    RadioGroup.OnCheckedChangeListener,
    CompoundButton.OnCheckedChangeListener {

    private var toolbar: Toolbar? = null
    protected var tvRight: TextView? = null
    protected var tvTitle: TextView? = null
    protected var btRight: TextView? = null
    protected var ivBack: ImageView? = null
    protected var ivRight: ImageView? = null
    /**
     * 列表页面默认list
     */
    protected val mList by lazy { ArrayList<Any>() }
    /**
     * 上下文context
     */
    protected lateinit var baseContext: Activity
    /**
     * RecyclerView数据管理的LayoutManager
     */
    protected lateinit var linearLayoutManager: LinearLayoutManager
    protected lateinit var gridLayoutManager: GridLayoutManager
    protected lateinit var staggeredGridLayoutManager: StaggeredGridLayoutManager
    /**
     * SlimAdapter的adapter
     */
    protected lateinit var mAdapter: SlimAdapter
    /**
     * SlimAdapter可加头部或底部的adapter
     */
    protected lateinit var mAdapterEx: SlimAdapterEx
    /**
     * 分页加载页数
     */
    protected var pageNum = 1
    /**
     * 分页总页数
     */
    protected var pageTotal = 1
    /**
     * 是否正在上拉加载中
     */
    protected var isLoadingMore = false
    /**
     * 列表选择时的位置标记，可做其他字段使用
     */
    protected var mPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        super.setContentView(R.layout.activity_base)
        transparentStatusBar(isTrans = false)

        initToolbar()
        baseContext = this
        ActivityStack.screenManager.pushActivity(this)

        //注册监听ViewModel的生命周期
        initViewModelEvent()
        getViewModel()?.let { lifecycle.addObserver(it) }
        if (getViewModelList().isNotEmpty()) {
            getViewModelList().forEach { lifecycle.addObserver(it) }
        }
    }

    protected fun setSuperContentView(layoutId: Int) {
        super.setContentView(layoutId)
    }

    /**
     * 设置沉浸状态栏和状态栏字体颜色
     *
     * @param isTrans    是否沉浸，true沉浸，false不沉浸
     * @param isDarkFont 状态栏字体是否深色，true深色，false亮色
     */
    @JvmOverloads
    protected fun transparentStatusBar(
        isTrans: Boolean = true,
        isDarkFont: Boolean = false
    ) {
        if (isTrans) {
            ultimateBarBuilder().apply {
                statusDark(isDarkFont)
                statusDrawable(ColorDrawable(Color.TRANSPARENT))
                if (isDarkFont) {
                    statusDrawable2(ColorDrawable(Color.parseColor("#55000000")))
                }
                applyNavigation(false)
            }
                .create()
                .immersionBar()
        } else {
            ultimateBarBuilder().apply {
                statusDark(isDarkFont)
                statusDrawable(ColorDrawable(getColorEx(R.color.colorPrimary)))
                if (isDarkFont) {
                    statusDrawable2(ColorDrawable(Color.parseColor("#55000000")))
                }
                applyNavigation(false)
            }
                .create()
                .drawableBar()
        }
    }

    /**
     * 沉浸状态栏，设置状态栏字体颜色和Toolbar是否可见
     *
     * @param isDarkFont 状态栏字体是否深色，true深色，false亮色
     * @param isVisible  Toolbar是否可见，true可见，false不可见
     */
    @JvmOverloads
    protected fun setTransparentAndToolbar(
        isDarkFont: Boolean = true,
        isVisible: Boolean = false
    ) {
        transparentStatusBar(true, isDarkFont)
        setToolbarVisibility(isVisible)
    }

    private fun initToolbar() {
        toolbar = findViewById(R.id.toolbar)
        if (toolbar != null) {
            setSupportActionBar(toolbar)
            val actionBar = supportActionBar
            if (actionBar != null)
                actionBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
        }
    }

    //初始化控件，改变中间和右侧标题
    @JvmOverloads
    protected open fun initTitle(
        title: String = "",
        name: String = ""
    ) {
        ivBack = findViewById(R.id.iv_nav_back)
        ivRight = findViewById(R.id.iv_nav_right)
        tvTitle = findViewById(R.id.tv_nav_title)
        tvRight = findViewById(R.id.tv_nav_right)
        btRight = findViewById(R.id.btn_nav_right)

        changeTitle(title, name)
    }

    //改变中间和右侧标题
    @JvmOverloads
    protected fun changeTitle(
        title: String = "",
        name: String = ""
    ) {
        if (tvTitle == null) tvTitle = findViewById(R.id.tv_nav_title)
        if (tvRight == null) tvRight = findViewById(R.id.tv_nav_right)

        if (title.isEmpty()) tvTitle?.invisible()
        else {
            tvTitle?.visible()
            tvTitle?.text = title
        }

        if (name.isEmpty()) tvRight?.invisible()
        else {
            tvRight?.visible()
            tvRight?.text = name
        }
    }

    //设置Toolbar是否可见
    protected fun setToolbarVisibility(isVisible: Boolean) {
        if (toolbar != null) toolbar!!.visibility = if (isVisible) View.VISIBLE else View.GONE
        findViewById<View>(R.id.divider).visibility = if (isVisible) View.VISIBLE else View.GONE
    }

    override fun setContentView(@LayoutRes layoutId: Int) {
        setContentView(View.inflate(this, layoutId, null))
    }

    override fun setContentView(view: View) {
        val rootLayout = findViewById<LinearLayout>(R.id.content_layout) ?: return
        rootLayout.addView(
            view,
            ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        )
        initToolbar()
    }

    //标题栏的返回按钮，onclick = "doClick"
    open fun doClick(v: View) {
        when (v.id) {
            R.id.iv_nav_back -> onBackPressed()
        }
    }

    //网络数据请求方法
    @JvmOverloads
    protected open fun getData(
        index: Int = 0,
        isLoading: Boolean = false
    ) {}

    //隐藏键盘
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v!!.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left
                    && event.x < right
                    && event.y > top
                    && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    override fun getIContext(): Context = this

    override fun getLifecycleOwner(): LifecycleOwner = this

    override fun showLoading(msg: String) {
        if (msg.isEmpty()) showLoadingDialog()
        else showLoadingDialog(msg)
    }

    override fun dismissLoading() {
        cancelLoadingDialog()
    }

    override fun finishView() {
        ActivityStack.screenManager.popActivities(this::class.java)
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

    override fun afterTextChanged(s: Editable) {}

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {}

    override fun onCheckedChanged(group: RadioGroup, checkedId: Int) {}

    override fun onClick(v: View) {}

}
